# --------------------------------------------------------------------------------
# hzy-generator
import random
import os
import string


# 生成一组随机数据  生成int、float或str类型
def generate_data(data_type, data_len, min_value=0, max_value=100, decimal_places=2):
    """
    data_type: str, 数据类型，可以是'int', 'float'或'str'
    data_len: int, 数据长度
    min_value: int/float, 数据最小值 默认为0
    max_value: int/float, 数据最大值 默认为100
    decimal_places: int, 浮点数的小数位数 默认为2

    生成str时,min_value和max_value和decimal_places参数无效,生成随机字符,字符长度为1,字符集为大小写字母和数字,长度为data_len
    """
    if not isinstance(data_len, int) or data_len <= 0:
        raise ValueError("data_len should be a positive integer.")
    if data_type not in ["int", "float", "str"]:
        raise ValueError("data_type should be 'int', 'float' or 'str'.")
    if not isinstance(min_value, (int, float)) or not isinstance(
        max_value, (int, float)
    ):
        raise ValueError("min_value and max_value should be numbers.")
    if min_value > max_value:
        raise ValueError("min_value should not be greater than max_value.")
    if not isinstance(decimal_places, int) or decimal_places < 0:
        raise ValueError("decimal_places should be a non-negative integer.")

    data = []
    if data_type == "int":
        data = [random.randint(min_value, max_value) for _ in range(data_len)]
    elif data_type == "float":
        data = [
            round(random.uniform(min_value, max_value), decimal_places)
            for _ in range(data_len)
        ]
    elif data_type == "str":
        # Generate a list of characters, each character is of length 1
        data = [
            random.choice(string.ascii_letters + string.digits) for _ in range(data_len)
        ]
    return data


# 保存数据到文件  空格分隔
def save_data(data, file_name):
    """
    data: list, 待保存的数据
    file_name: str, 文件名

    将数据保存到文件中，数据之间用空格分隔
    """
    if not isinstance(file_name, str):
        raise ValueError("file_name should be a string.")
    if not data:
        raise ValueError("data should not be empty.")

    with open(file_name, "w") as f:
        f.write(" ".join(map(str, data)))


# 从文件中读取数据
def read_data(file_name):
    """
    file_name: str, 文件名

    从文件中读取数据，数据之间用空格分隔
    """
    if not isinstance(file_name, str):
        raise ValueError("file_name should be a string.")
    if not os.path.isfile(file_name):
        raise FileNotFoundError(f"{file_name} does not exist.")

    with open(file_name, "r") as f:
        data = f.read().split()
    return data


# 生成一组随机数据并保存到文件
def generate_and_save_data(
    data_type, data_len, file_name, min_value=0, max_value=100, decimal_places=2
):
    data = generate_data(data_type, data_len, min_value, max_value, decimal_places)
    save_data(data, file_name)


# --------------------------------------------------------------------------------